<?php

namespace common\components\image_beds;

use common\components\fs\Fs;
use common\components\wtools\tools\FileHelper;
use common\components\wtools\tools\Model;
use common\models\db\Files;
use common\Tools;
use finfo;
use yii\base\Component;
use yii\di\Instance;

class EasyImageFs extends Fs
{
    public static function getComponentId(): string
    {
        return 'easyImageFs';
    }

    /**
     * @var EasyImage $easyImage
     */
    public $easyImage = 'easyImage';

    public function init()
    {
        $this->easyImage = Instance::ensure($this->easyImage, EasyImage::className());
        parent::init();
    }

    public function uploadByTmpFile($tmp)
    {
        $tmpFile = $tmp['tmp_name'];
        $url = $this->uploadByFileRoot($tmpFile);
        return $url;
    }

    public function uploadByFileRoot($fileRoot)
    {
        $url = $this->easyImage->upload($fileRoot);
        return $url;
    }

    public function uploadBase64($idFileName, $base64)
    {
        $tmpFilePath = \Yii::getAlias('@uploads_root/tmp/').$idFileName;
        if (!is_dir(dirname($tmpFilePath))) {
            FileHelper::createDirectory(dirname($tmpFilePath));
        }
        file_put_contents($tmpFilePath, base64_decode($base64));
        $url = $this->easyImage->upload($tmpFilePath);
        unlink($tmpFilePath);
        return $url;
    }

    /**
     * @return Files|null
     * @throws \yii\base\Exception
     */
    public function saveFile($url)
    {
        $this->file->locate_path = str_replace($this->easyImage->baseUrl, '', $url);
        if (!$this->file->save()) {
            throw new \Exception("文件保存失败：".Model::getModelError($this->file));
        }
        return $this->file;
    }

    /**
     * @return string
     */
    public function getAbUrl()
    {
        return $this->easyImage->baseUrl . $this->file->locate_path;
    }
}
